<template>
    <div class="read-container">
        <div class="header-title">
          <h3>读书点亮生活,知识创新未来</h3>
          <p class="prompt-text">亲爱的书友，<span class="blod-text">11月3日樊老师大型演讲</span>是<span class="blod-text">"第十一届海峡两岸文化交易博览会"</span>（简称<span class="blod-text">文博会</span>）主论坛之一，也是本次文博会规模最大的论坛。
</p>
<p class="prompt-text">整个文博会安检系统由公安部门直接负责，公安部门对于安检系统非常严格，要求实名制一人一证，方可入场。</p>
<p class="prompt-text">由于集中进场的人流大，为避免书友现场排队办证时间过长，导致错过演讲，我们将为书友提供提前办理证件服务，书友们可直接到现场<span class="blod-text">"樊登读书"</span>书友服务处领取入场证件。</p>
<p><span class="blod-text">特别说明</span>：</p>
<p>（1）本次书友提交的信息仅用于办理文博会入场证件，我们确保信息不泄露。</p>
<p>（2）统一办理的入场证为文博会所有展馆通行证件，请书友同时携带文博会入场证及千人演讲电子门票进入会场。
</p>
<p style="margin-top:10px;">请书友填写以下信息：</p>
        </div>
        <div class="sign-form">
            <van-cell-group>
                <van-field
                  v-model="userInfo.Name"
                  required
                  label="真实姓名"
                  input-align="right"
                  placeholder="请输入真实姓名"
                />
                <van-field
                  v-model="userInfo.Phone"
                  required
                  label="手机"
                  input-align="right"
                  readonly
                />
                <van-cell title="性别" required>
                    <van-radio-group v-model="userInfo.Sex">
                        <van-radio name="男">男</van-radio>
                        <van-radio name="女">女</van-radio>
                    </van-radio-group>
                </van-cell>
                <van-field
                  v-model="userInfo.Country"
                  required
                  label="国家/地区"
                  input-align="right"
                  placeholder="请选择所在国家或地区"
                  readonly
                  icon="arrow"
                  @click-icon="showCoutryPicker"
                  @click="showCoutryPicker"
              />
              <van-field
                v-if="userInfo.Country=='中国大陆'"
                v-model="userInfo.ProvinceCity"
                required
                label="户籍省市"
                input-align="right"
                placeholder="请选择户籍所在省市"
                readonly
                icon="arrow"
                @click-icon="showAreaPicker"
                @click="showAreaPicker"
            />
              <van-field
                  v-model="certificateType"
                  required
                  label="证件类别"
                  input-align="right"
                  placeholder="请选择证件类别"
                  readonly
                  icon="arrow"
                  @click-icon="showCertiPicker"
                  @click="showCertiPicker"
              />
              <van-field
                  v-model="userInfo.IDCard"
                  required
                  label="证件号(务必填写正确)"
                  input-align="right"
                  placeholder="请输入正确的证件号"
              />
              <van-field
                v-model="userInfo.Company"
                required
                label="单位名称"
                input-align="right"
                placeholder="请输入单位名称"
              />
              <van-field
                v-model="userInfo.Post"
                required
                label="职务"
                input-align="right"
                placeholder="请输入职务"
              />
              <div class="file-image">
                <van-cell title="照片(一寸免冠彩照、纯底色)" is-link required value="点击上传" @click="showFileModel">
                    <img id="img" class="preview-image" v-if="userInfo.HeadImage!=''" :src="userInfo.HeadImage" @click="previewImg">
                </van-cell>
            </div>
            <div class="submit-btn">
              <van-button size="large" type="primary" @click="submitUserInfo">提交</van-button>
            </div>
            </van-cell-group>
        </div>
        <!-- 上传图片 -->
        <van-actionsheet v-model="fileModel">
                <div class="actionsheet-title">请上传照片</div>
                <div class="actionsheet-row">
                    <span>从相册中选择</span>
                    <input type="file" accept="image/*" @change="fileChange" @click="fileToggle(0)">
                </div>
                <div class="actionsheet-row">
                    <span>拍照</span>
                    <input type="file" capture="camera" accept="image/*" @change="fileChange" @click="fileToggle(0)">
                </div>
                <div class="actionsheet-close" @click="fileToggle(0)">取消</div>
            </van-actionsheet>
            <!-- 国家、地区选择器 -->
            <van-popup v-model="countryPicker" position="bottom">
                <van-picker show-toolbar :columns="countryArry" @cancel="countryCancel" @confirm="countryConfirm" />
            </van-popup>
            <!-- 选择省市区 -->
            <van-popup v-model="areaPicker" position="bottom">
                <van-area :area-list="areaList" :columns-num="2" title="选择省市"  @cancel="areaCancel" @confirm="areaConfirm" />
            </van-popup>
            <!-- 选择证件类型 -->
            <van-popup v-model="certificatePicker" position="bottom">
                <van-picker show-toolbar :columns="certificateList" @cancel="certiCancel" @confirm="certiConfirm" />
            </van-popup>
    </div>
</template>

<script>
import axios from 'axios'
import { ImagePreview } from 'vant'
import areaData from '../../static/js/area.js'
export default {
  name: 'signPage',
  data () {
    return {
      fileModel: false,
      countryPicker: false,
      areaPicker: false,
      certificatePicker: false,
      certificateType: '',
      areaList: areaData,
      certificateList: [
        { text: '身份证', value: 'IDCard' },
        { text: '军官证', value: 'Armymen' },
        { text: '护照', value: 'Passport' },
        { text: '台胞证', value: 'Taiwan' },
        { text: '回乡证', value: 'ReentryPermit' }
      ],
      countryArry: [
        { text: '中国大陆', value: '中国大陆' },
        { text: '中国香港', value: '中国香港' },
        { text: '中国澳门', value: '中国澳门' },
        { text: '中国台湾', value: '中国台湾' },
        { text: '墨西哥', value: '墨西哥' },
        { text: '巴西', value: '巴西' },
        { text: '南非', value: '南非' },
        { text: '印度', value: '印度' },
        { text: '俄罗斯', value: '俄罗斯' },
        { text: '新加坡', value: '新加坡' },
        { text: '泰国', value: '泰国' },
        { text: '马来西亚', value: '马来西亚' },
        { text: '印度尼西亚', value: '印度尼西亚' },
        { text: '巴基斯坦', value: '巴基斯坦' },
        { text: '菲律宾', value: '菲律宾' },
        { text: '波兰', value: '波兰' },
        { text: '其他国家和地区', value: '其他国家和地区' }
      ],
      userInfo: {
        // 姓名
        Name: '',
        // 性别
        Sex: '男',
        // 国家/地区
        Country: '',
        // 省/市
        ProvinceCity: '',
        Province: '',
        City: '',
        District: '',
        // 证件类型
        CertificateTypeEnum: '',
        // 证件号
        CertificateNum: '',
        IDCard: '',
        // 手机
        Phone: '',
        // 单位
        Company: '',
        // 职务
        Post: '',
        // 头像
        HeadImage: '',
        // st
        ST: '',
        // 门票码
        Number: ''
      }
    }
  },
  created () {
    console.log(window.navigator.userAgent)
    this.userInfo.ST = this.$route.query.st
    this.userInfo.Number = this.$route.query.number
    var that = this
    axios({
      url:
        that.baseUrl +
        '/api/exhibition/getAttendUser/' +
        that.$route.query.number +
        '/' +
        that.$route.query.st,
      method: 'GET'
    })
      .then(res => {
        // console.log(res)
        if (res.data.IDCard == null || res.data.IDCard == '') {
          that.userInfo.Name = res.data.Name
          that.userInfo.Phone = res.data.Phone
        } else {
          window.location.href =
            that.baseUrl +
            '/Q/' +
            that.$route.query.st +
            '/true?phone=' +
            res.data.Phone
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  methods: {
    showFileModel () {
      this.fileModel = true
    },
    fileToggle (state) {
      if (state) {
        this.fileModel = true
      } else {
        this.fileModel = false
      }
    },
    isWeixin () {
      var ua = navigator.userAgent.toLowerCase()
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true
      } else {
        return false
      }
    },
    fileChange (e) {
      this.fileModel = false
      var that = this
      var reader = new FileReader()
      // var imgSize = e.target.files[0].size
      reader.readAsDataURL(e.target.files[0])
      reader.onload = function (e) {
        var dataURL = e.target.result || e.srcElement.result
        // if (that.isWeixin) {
        //   that.userInfo.HeadImage = dataURL
        // } else {
        //   if (imgSize > 1024 * 1024) {
        var imaged = new Image()
        imaged.src = dataURL
        imaged.onload = function () {
          var canvas = document.createElement('canvas')
          var ctx = canvas.getContext('2d')
          var w = 0
          var h = 0
          if (this.width > this.height) {
            h = 1000
            var scale = this.width / this.height
            h = h > this.height ? this.height : h
            w = h * scale
          } else {
            w = 1000
            //   var scale = this.width / this.height
            w = w > this.width ? this.width : w
            h = w / scale
          }
          var anw = document.createAttribute('width')
          var anh = document.createAttribute('height')
          anw.value = w
          anh.value = h
          canvas.setAttributeNode(anw)
          canvas.setAttributeNode(anh)
          ctx.drawImage(this, 0, 0, w, h)
          dataURL = canvas.toDataURL('image/jpg', 0.8)
          that.userInfo.HeadImage = dataURL
          // imgSize = that.convertToBinary(dataURL).size
          // if (imgSize < 1024 * 1024) {
          //   that.userInfo.HeadImage = dataURL
          // } else {
          //   that.$toast('上传图片过大，请重新上传！')
          // }
        }
        // } else {
        //   that.userInfo.HeadImage = dataURL
        // }
        // }
      }
    },
    showCoutryPicker () {
      this.countryPicker = true
    },
    countryCancel () {
      this.countryPicker = false
    },
    countryConfirm (value, index) {
      this.userInfo.Country = value.text
      this.countryPicker = false
    },
    showAreaPicker () {
      this.areaPicker = true
    },
    areaCancel () {
      this.areaPicker = false
    },
    areaConfirm (value) {
      console.log(value)
      this.userInfo.ProvinceCity = value[0].name + ' ' + value[1].name
      this.userInfo.Province = value[0].name
      this.userInfo.City = value[1].name
      // this.userInfo.District = value[2].name
      this.areaPicker = false
    },
    showCertiPicker () {
      this.certificatePicker = true
    },
    certiCancel () {
      this.certificatePicker = false
    },
    certiConfirm (value) {
      this.certificatePicker = false
      this.userInfo.CertificateTypeEnum = value.value
      this.certificateType = value.text
    },
    trims (str) {
      return str.replace(/(^\s*)|(\s*$)/g, '')
    },
    previewImg (e) {
      e.stopPropagation()
      var imgSrc = []
      imgSrc.push(this.userInfo.HeadImage)
      ImagePreview(imgSrc)
    },
    submitUserInfo () {
      var that = this
      console.log(this.userInfo)
      if (this.userInfo.Country == '') {
        this.$toast('请选择国别')
      } else if (
        this.userInfo.Country == '中国大陆' &&
        this.userInfo.City == ''
      ) {
        this.$toast('请选择户籍省市')
      } else if (this.certificateType == '') {
        this.$toast('请选择证件类别')
      } else if (this.trims(this.userInfo.IDCard) == '') {
        this.$toast('请输入证件号')
      } else if (this.trims(this.userInfo.Company) == '') {
        this.$toast('请输入单位名称')
      } else if (this.trims(this.userInfo.Post) == '') {
        this.$toast('请输入职务')
      } else if (this.userInfo.HeadImage == '') {
        this.$toast('请上传照片')
      } else {
        // this.$toast.loading({
        //   mask: true,
        //   message: '信息提交中...',
        //   duration: 0
        // })
        axios({
          method: 'POST',
          url: that.baseUrl + '/api/exhibition/UpdateUser',
          contentType: 'application/json; charset=utf-8',
          data: that.userInfo
        })
          .then(res => {
            this.$dialog.alert({
              message: res
            })
            // that.$toast.clear()
            if (res.data.State) {
              window.location.href =
                that.baseUrl +
                '/Q/' +
                that.userInfo.ST +
                '/true?phone=' +
                that.userInfo.Phone
            } else {
              that.$toast(res.data.Message)
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    }
  },
  watch: {
    'userInfo.IDCard': function (val, oldVal) {
      if (this.trims(val).length > 18) {
        this.userInfo.IDCard = val.slice(0, 18)
      }
    }
  }
}
</script>

<style>
@import "../assets/css/style.css";
@import "../assets/css/clipper.css";
</style>
